<?php

function uissync_dashboard_form($form, &$form_state){
    
  $form = uissync_dashboard_form_functions($form);
  
  $form = uissync_dashboard_form_services($form);
  
  $form = uissync_dashboard_form_settings($form);


  $form['submit'] = array(
      '#type'	 => 'submit',
      '#value' => t('Save')
  );

  return $form;
}


/**
 * save the settings from the functions and the services from the uissync dashboard 
 */
function uissync_dashboard_form_submit($form, &$form_state){
  
  try {
    
    // truncate the db and refill again with new settings
    db_truncate('uis_functies_roles')->execute();
    
    // check if there is something in functions
    if (isset($form_state['values']['functions'])) {
      
      $fieldsToSave = array('fid', 'rid');

      $insert = db_insert('uis_functies_roles')->fields($fieldsToSave);

      foreach ($form_state['values']['functions'] as $fid => $values) {
        
        foreach ($values as $rid) {
          
          if ($rid > 0) {
            
            $insert->values( array('fid' => $fid, 'rid' => $rid) );
          
          }
        }
        
      }

      $insert->execute();
    }
    
    // save services (mostly the same as functions
    db_truncate('uis_services_roles')->execute();
    
    if (isset($form_state['values']['services'])) {

      $fieldsToSave = array('sid', 'rid');

      $insert = db_insert('uis_services_roles')->fields($fieldsToSave);

      foreach ($form_state['values']['services'] as $sid => $values) {
        
        foreach ($values as $rid) {
          
          if ($rid > 0) {
            
            $insert->values( array('sid' => $sid, 'rid' => $rid) );
          
          }
          
        }
        
      }

      $insert->execute();
      
    }
    
    drupal_set_message(t('Settings are saved'));
  
  } catch (PDOException $e) {
    drupal_set_message(t('Unable to save settings'), 'error');
    
    watchdog('uis_sync', $e->getMessage());
  }
  
  variable_set('uissync_abbreviation', $form_state['values']['settings']['abbr']);
  variable_set('uissync_member_number', $form_state['values']['settings']['nr']);
}

/**
 * add the functions fieldset with checkboxes
 */
function uissync_dashboard_form_functions($form){
    
    // create the group container
    $form['functions'] = array(
	'#type' => 'fieldset',
	'#title' => t('Functions'),
	'#collapsible' => true,
	'#collapsed' => false,
        '#tree' => true,
        '#theme' => 'uissync_fieldset_checkboxes',
        '#uissync_table_title' => t('Function name'),
        '#uissync_table_empty' => t('functions')
    );
    
    $result = db_query("SELECT *, GROUP_CONCAT(rl.rid) as 'roles'
                        FROM {uis_functies} AS f
                        INNER JOIN {uis_functies_roles} AS r ON ( f.fid = r.fid )
                        INNER JOIN {role} AS rl ON ( r.rid = rl.rid )
                        GROUP BY f.fid
                        ORDER BY f.naam ASC;");
   
    
    foreach($result->fetchAll() as $row){
        $roles = explode(',', $row->roles);
        $manager = (($row->verantwoordelijke) ? ' (' . t('Manager') . ')' : '');
        
        // add checkboxes for this row with a checkbox for each role
        $form['functions'][$row->fid] = array(
              '#type' => 'checkboxes',
              '#title' => $row->naam . $manager,
              '#default_value' => array_values($roles),
              '#options' => user_roles());
	
    }
    
    return $form;
}

/**
 * add the service fieldset with checkboxes
 */
function uissync_dashboard_form_services($form){
    
    // create the group container
    $form['services'] = array(
	'#type' => 'fieldset',
	'#title' => t('Service'),
	'#collapsible' => true,
	'#collapsed' => false,
        '#tree' => true,
        '#theme' => 'uissync_fieldset_checkboxes',
        '#uissync_table_title' => t('Service name'),
        '#uissync_table_empty' => t('services')
    );
    
    // createn the list of functions assigned to a role
    
    $result = db_query("SELECT *, GROUP_CONCAT(rl.rid) as 'roles'
                        FROM {uis_services} AS s
                        INNER JOIN {uis_services_roles} AS r ON ( s.sid = r.sid )
                        INNER JOIN {role} AS rl ON ( r.rid = rl.rid )
                        GROUP BY s.sid
                        ORDER BY s.naam ASC;");
   
    
    foreach($result->fetchAll() as $row){
        $roles = explode(',', $row->roles);
        
        $form['services'][$row->sid] = array(
              '#type' => 'checkboxes',
              '#title' => $row->naam,
              '#default_value' => array_values($roles),
              '#options' => user_roles());
	
    }
    
    return $form;
}

function uissync_dashboard_form_settings($form) {
  // create the group container
    $form['settings'] = array(
	'#type' => 'fieldset',
	'#title' => t('Settings'),
	'#collapsible' => true,
	'#collapsed' => true,
        '#tree' => true,
    );
    
    $query = db_select('field_config_instance', 'i');
    $query->fields('i', array('field_name'));
    $query->condition('i.entity_type', 'profile2');
    $result = $query->execute();
    
    $options = array(0 => t('Not used'));
    
    foreach($result->fetchAll() as $row){
      $options[$row->field_name] = $row->field_name;
    }
    
    
    $form['settings']['abbr'] = array(
      '#type' => 'select',
      '#title' => t('Abbreviation'),
      '#description' => t('Select the field to match the abbreviation'),
      '#options' => $options,
      '#default_value' => variable_get('uissync_abbreviation')
    );
    
    $form['settings']['nr'] = array(
      '#type' => 'select',
      '#title' => t('Member number'),
      '#description' => t('Select the field to match the member number'),
      '#options' => $options,
      '#default_value' => variable_get('uissync_member_number')
    );
    
    return $form;
}

/**
 * add a new function to the list
 */
function uissync_function_add($form){
  
  // fetch all the functions for the select list
  $result = db_query("select * from {uis_functies} order by naam asc;");
  $options = array();

  foreach($result->fetchAll() as $row){
    $options[$row->fid] = $row->naam . (($row->verantwoordelijke) ? ' (' . t('Manager') . ')' : '');
  }

  $form['function'] = array(
      '#type' => 'select',
      '#title' => t('Function'),
      '#options' => $options
  );

  $form['roles'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Role'),
      '#options' => user_roles()
  );
  
  $form['submit'] = array(
	'#type'	 => 'submit',
	'#value' => t('Add')
    );
  
  // if there are no options to select, disable the form and show message
  if (empty($options)) {
    $form['submit']['#disabled'] = true;
    $form['roles']['#disabled'] = true;
    
    drupal_set_message(t('No functions available'), 'warning');
  }
  
  
  return $form;
}

/**
 * merge settings, in case the function is already in the list
 */
function uissync_function_add_submit ($form, &$form_state) {
  foreach ($form_state['values']['roles'] as $rid => $add) {
    if ($add > 0) {
      db_merge('uis_functies_roles')
        ->key(array('rid' => $rid, 'fid' => $form_state['values']['function']))
        ->execute(); 
    }
  }
  
  
  drupal_set_message(t('Function is added'));
  
  $form_state['redirect'] = 'admin/config/people/uissync';
}

/**
 * add services to the list
 */
function uissync_service_add($form){
  
  $result = db_query("select * from {uis_services} order by naam asc;");
  $options = array();

  foreach($result->fetchAll() as $row){
    $options[$row->sid] = $row->naam;
  }

  $form['services'] = array(
      '#type' => 'select',
      '#title' => t('Services'),
      '#options' => $options
  );

  $form['roles'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Role'),
      '#options' => user_roles()
  );
  
  $form['submit'] = array(
	'#type'	 => 'submit',
	'#value' => t('Add')
    );
  
  // disable the form if no services are available
  if (empty($options)) {
    $form['submit']['#disabled'] = true;
    $form['roles']['#disabled'] = true;
    
    drupal_set_message(t('No services available'), 'warning');
  }
  
  return $form;
}

function uissync_service_add_submit($form, &$form_state){
  
  foreach ($form_state['values']['roles'] as $rid => $add) {
    if ($add > 0) {
      db_merge('uis_services_roles')
        ->key(array('rid' => $rid, 'sid' => $form_state['values']['services']))
        ->execute(); 
    }
  }
  
  drupal_set_message(t('Function is added'));
  
  $form_state['redirect'] = 'admin/config/people/uissync';
}

/**
 * convert the checkboxes in a fieldset in themed table
 * 
 * value for the first culmn is the title of the checkboxes
 * 
 * extra properties for the fieldset array ara
 * #uissync_table_title : the title for the first culmn of the table
 * #uissync_table_empty : the text displayed when no rows where found
 */
function theme_uissync_fieldset_checkboxes($element) {  
  $element = array_shift($element);

  $rows = array();
  
  foreach(element_children($element) as $value){
    $row = array();
    
    $row[] = $element[$value]['#title'];
    
    foreach (element_children($element[$value]) as $key) {
      $element[$value][$key]['#title_display'] = 'invisible';
      $row[] = drupal_render($element[$value][$key]);
    }
    
    $rows[] = $row;
    
  }
  
  $table = array(
      'rows' => $rows,
      'header' => array($element['#uissync_table_title']) + user_roles(),
      'empty' => t('No @name found', array('@name' => $element['#uissync_table_empty'])),
    );
  
  return theme('table', $table);

}